package fr.poc.eureka;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;

import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.appinfo.MyDataCenterInstanceConfig;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.discovery.DefaultEurekaClientConfig;
import com.netflix.discovery.DiscoveryManager;

import fr.poc.app.Application;

public class PocEurekaService {

	private static final DynamicPropertyFactory configInstance = com.netflix.config.DynamicPropertyFactory
			.getInstance();

	private static final Logger logger = LoggerFactory
			.getLogger(PocEurekaService.class);

	static public void startService() {
		int sleepSeconds = 10; // Application initialization and running
								// simulation time

		// Register with Eureka
		DiscoveryManager.getInstance().initComponent(
				new MyDataCenterInstanceConfig(),
				new DefaultEurekaClientConfig());

		// A good practice is to register as STARTING and only change status to
		// UP
		// after the service is ready to receive traffic
		logger.info("Registering service to eureka with STARTING status");
		ApplicationInfoManager.getInstance().setInstanceStatus(
				InstanceStatus.STARTING);
	}

	static private void registerWithEurekaServer() {
		// Now we change our status to UP
		logger.info("Done sleeping, now changing status to UP");
		ApplicationInfoManager.getInstance().setInstanceStatus(
				InstanceStatus.UP);

		String vipAddress = configInstance.getStringProperty(
				"eureka.vipAddress", "pocservice.mydomain.net").get();
		InstanceInfo nextServerInfo = null;
		while (nextServerInfo == null) {
			try {
				nextServerInfo = DiscoveryManager.getInstance()
						.getDiscoveryClient()
						.getNextServerFromEureka(vipAddress, false);
			} catch (Throwable e) {
				logger.info("Waiting for service to register with eureka..");

				try {
					Thread.sleep(10000);
				} catch (InterruptedException e1) {
					logger.error("error in pausing", e1);
				}

			}
		}
		logger.info("Service started and ready to process requests..");
	}

	// start of static block
	static {
		
		

	}

	// end of static block

	public static void main(String[] args) {

		startService();
		SpringApplication.run(Application.class, args);
		registerWithEurekaServer();

	}

}
